package com.kanshu.ksgb.fastread.doudou.module.personal.service;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.errorlog.utils.ErrorLogUtil;
import com.kanshu.ksgb.fastread.doudou.common.business.event.RedPointEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.ResponseData;
import com.kanshu.ksgb.fastread.doudou.common.net.SuperCallBack;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.DynamicSimpleRetrofit;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver;
import com.kanshu.ksgb.fastread.doudou.common.net.rx.NothingObserverUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.ConfigService;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ActivityMgr;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin.BindHelper;
import com.kanshu.ksgb.fastread.doudou.module.login.utils.SSOManager;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.MakeMoneyConfig;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.ConfigBean;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.CustomerServiceInfo;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.EveryDayDialogInfo;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.ReadFeedbackBean;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.SignInBeanNew;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.SignInData;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UserBean;
import com.kanshu.ksgb.fastread.doudou.module.personal.dialog.DialogCreator;
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterPresenter;
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService;
import com.kanshu.ksgb.fastread.doudou.module.personal.utils.PaymentVersion;
import com.kanshu.ksgb.fastread.doudou.module.personal.utils.UserInfoUtils;
import com.kanshu.ksgb.fastread.doudou.module.signin.activity.NewSignInActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;
import retrofit2.Call;

/**
 * 作者    wcy
 * 时间    2018/12/4 16:59
 * 文件    doudou
 * 描述
 */
@Route(path = ARouterConfig.INIT_SERVICE)
public class ConfigServiceImpl implements ConfigService {
    public Subject<Integer> lifeCyclerSubject;
    PersonCenterPresenter mPersonCenterPresenter;
    Context mContext;
    @Override
    public void initConfig() {
        // 单点登录定时器开启
        SSOManager.getInstance().start();
        // 检查用户偏好
        checkReadPreferences();
        // 应用启动上报
        pVUVLaunchApp();
        // 拉取配置
        getConfig();
        //每日弹窗
        checkEveryDayDialog();
    }

    @Override
    public void checkRedPoint() {
        // 获取签到信息
        doShowSign();
        // 检查是否有帮助反馈信息
        checkHelpFeedback();
    }

    @Override
    public void registerIdByDevice() {
        BindHelper.regiserByDeviceId();
    }

    @Override
    public void init(Context context) {
        mContext = context;
        lifeCyclerSubject = PublishSubject.create();
        mPersonCenterPresenter = new PersonCenterPresenter(lifeCyclerSubject);
    }

    /**
     * 应用启动上报
     */
    private void pVUVLaunchApp() {
        RetrofitHelper helper = RetrofitHelper.getInstance();
        helper.createService(DynamicSimpleRetrofit.class, PersonCenterService.class).pVUVLaunchApp()
                .compose(asyncRequest())
                .subscribe(NothingObserverUtils.nothingObserver);
    }

    public <T> ObservableTransformer<T, T> asyncRequest() {
        return upstream -> upstream .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .takeUntil(lifeCyclerSubject);
    }

    public static void getConfig() {
        checkIsFreeVersion();
        getMakeMoneyConfig();
        getClearCacheConfig();
        getCustomerServiceQQ();
        // http日志上报
        ErrorLogUtil.httpLogSwitch();
    }

    public static void checkIsFreeVersion() {
        PaymentVersion paymentVersion = new PaymentVersion(Xutils.getContext());
        paymentVersion.checkIsFreeVersion();
    }

    private static void getMakeMoneyConfig() {
        PersonCenterPresenter presenter = new PersonCenterPresenter(null);
        presenter.getMakeMoneyConfig(new INetCommCallback<MakeMoneyConfig>() {
            @Override
            public void onResponse(MakeMoneyConfig makeMoneyConfig) {
                if (makeMoneyConfig != null) {
                    MMKVDefaultManager.getInstance().setEnableMakeMoneyModule(makeMoneyConfig.is_open == 1);
                    //保存服务器的阅读时间
                    MMKVDefaultManager.getInstance().saveServerReadTime(makeMoneyConfig.ad_minute + "#" + makeMoneyConfig.ad_type);
                }
            }

            @Override
            public void onError(int code, String errDesc) {

            }
        });
    }

    private static void getCustomerServiceQQ() {
        RetrofitHelper.getInstance().createService(PersonCenterService.class).getCustomerServiceQQ().enqueue(new SuperCallBack<CustomerServiceInfo>() {
            @Override
            public void onSuccess(Call<ResponseData<CustomerServiceInfo>> call, CustomerServiceInfo data) {
                if (data != null && !TextUtils.isEmpty(data.getQq())) {
                    MMKVDefaultManager.getInstance().setCustomerServiceQQ(data.getQq());
                }
            }

            @Override
            public void onFailure(Call<ResponseData<CustomerServiceInfo>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }

    private static void getClearCacheConfig() {
        UserInfoUtils.getConfig(new INetCommCallback<ConfigBean>() {
            @Override
            public void onResponse(ConfigBean configBean) {
                if (configBean != null) {
                    // 清除缓存配置
                    MMKVDefaultManager.getInstance().setClearCache(configBean.is_test_channel == 1 ? true : false);
                }
            }

            @Override
            public void onError(int code, String errDesc) {

            }
        });
    }

    /*
      检测是否需要弹出阅读偏好
    */
    private void checkReadPreferences(){
        RetrofitHelper.getInstance()
                .createService(PersonCenterService.class)
                .checkReadPreferences()
                .enqueue(new SuperCallBack<UserBean>() {
                    @Override
                    public void onSuccess(Call<ResponseData<UserBean>> call, UserBean data) {
                        if (data != null) {
                            UserUtils.saveUserId(data.user_id);
                        } else { // data为空则可以弹窗， 否则不能弹窗
                            ARouterUtils.toActivity(ARouterConfig.PERSONAL_READ_PREFERENCES, "isBack", true);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseData<UserBean>> call, Throwable t) {
                        super.onFailure(call, t);
                        Log.d("checkReadPreferences", t !=null ? t.toString() : "Throwable is null");
                    }
                });
    }

    /**
     * 每日弹窗
     */
    private void checkEveryDayDialog() {
        if (MMKVDefaultManager.getInstance().needShowEveryDayDialog()) {
            RetrofitHelper.getInstance()
                    .createService(PersonCenterService.class)
                    .getEveryDayDialogInfo()
                    .enqueue(new SuperCallBack<EveryDayDialogInfo>() {
                        @Override
                        public void onSuccess(Call<ResponseData<EveryDayDialogInfo>> call, EveryDayDialogInfo data) {
                            if (data != null && !TextUtils.isEmpty(data.getImg_url())) {
                                Activity activity = ActivityMgr.getInstance().peek();
                                if (activity == null || activity.isFinishing()) {
                                    return;
                                }
                                DialogCreator.getEveryDayDialog(activity, data.getImg_url(), data.getJump_url()).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseData<EveryDayDialogInfo>> call, Throwable t) {
                            super.onFailure(call, t);
                            Log.d("checkReadPreferences", t !=null ? t.toString() : "Throwable is null");
                        }
                    });
        }
    }

    private void doShowSign() {
        mPersonCenterPresenter.getSignData(new BaseObserver<SignInData>() {
            @Override
            public void onResponse(BaseResult<SignInData> listBaseResult, SignInData signInBeanNews, Disposable disposable) {
                boolean signedToday = false;
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(signInBeanNews.other.current_time * 1000);
                int dayInWeek = calendar.get(Calendar.DAY_OF_WEEK);
                dayInWeek = NewSignInActivity.Companion.getDaysInWeek()[dayInWeek - 1];
                if (signInBeanNews.lists != null && !signInBeanNews.lists.isEmpty()) {
                    for (SignInBeanNew item : signInBeanNews.lists) {
                        if (dayInWeek == item.week && item.signin == 1) {
                            signedToday = true;
                            break;
                        }
                    }
                }
                StorageUtils.setPreference(mContext, Constants.SP_NAME, "signed_today_" + UserUtils.getUserId(), !signedToday);
                RedPointEvent event = new RedPointEvent();
                // 签到信息
                event.obj1 = signInBeanNews;
                // 是否签到信息
                event.obj2 = signedToday;
                EventBus.getDefault().post(event);
            }

            @Override
            public void onError(int code, String errDesc) {
                super.onError(code, errDesc);
            }
        });
    }

    // 检测是否有意见反馈信息
    private void checkHelpFeedback() {
        mPersonCenterPresenter.checkReadFeedback(new BaseObserver<ReadFeedbackBean>() {
            @Override
            public void onResponse(BaseResult<ReadFeedbackBean> result, ReadFeedbackBean readFeedbackBean, Disposable disposable) {
                StorageUtils.setPreference(mContext, Constants.SP_NAME, "is_read_feedback_" + UserUtils.getUserId(), TextUtils.equals("0", readFeedbackBean.is_read));
                RedPointEvent event = new RedPointEvent();
                event.obj = true;
                EventBus.getDefault().post(event);
            }

            @Override
            public void onError(int code, String errDesc) {
                super.onError(code, errDesc);
            }
        });
    }

}
